package com.coding;

import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import com.alibaba.fastjson.JSONObject;
import com.coding.component.*;
import com.coding.config.AppConfig;
import com.coding.http.ApiService;
import com.coding.model.ExcelModel;
import com.coding.model.QueryModel;
import com.coding.util.ToolUtil;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;

public class WindowMain extends JFrame {

    //自定义圆角输入框边界线
    private static MyLineBorder myLineBorder = new MyLineBorder(new Color(192, 192, 192), 1, true);

    // 用户信息
    private static JLabel userId;
    private static JTextField userName;
    private static JPasswordField password;

    private static MyButton slectUserBtn;

    private static MyButton resetPasswordBtn;

    private static JLabel account;

    // 输入框
    private static MJTextField keyWord;
    private static MonthChooser startMonth;
    private static MonthChooser endMonth;
    private static DateChooser excelStartDay;
    private static DateChooser excelEndDay;

    // 按钮组
    private static MyButton bt1;
    private static MyButton bt2;
    private static MyButton bt3;
    private static MyButton bt4;
    private static MyButton bt5;
    private static MyButton bt6;

    private static MyButton bt7;


    private static JTextArea jTextArea;


    private static JWebBrowser webBrowser;

    public static void main(String[] args) {

        UIUtils.setPreferredLookAndFeel();
        NativeInterface.open();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("电费整合系统");
                frame.setLayout(new BorderLayout());
                frame.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowMain.class.getResource("/icon.png")));

                new WindowMain().initPage(frame);


                //让窗体可见
                frame.setVisible(true);
                //重置窗体大小
                frame.setResizable(true);
                // 设置窗体的宽度、高度
                frame.setSize(1200, 900);
                // 设置窗体居中显示
                frame.setLocationRelativeTo(null);
            }
        });
        NativeInterface.runEventPump();
    }

    /**
     * 初始化控件
     */
    private void initPage(JFrame frame) {

        // 隐藏
        userId = new JLabel();
        userId.setVisible(false);

        userName = new JTextField();
        userName.setFocusable(true);
        userName.setBorder(myLineBorder);
        userName.setPreferredSize(new Dimension(100, 25));

        password = new JPasswordField();
        password.setFocusable(true);
        password.setBorder(myLineBorder);
        password.setPreferredSize(new Dimension(100, 25));

        account = new JLabel();
        account.setPreferredSize(new Dimension(200, 25));

        slectUserBtn = new MyButton("登录");
        slectUserBtn.setPreferredSize(new Dimension(60, 25));
        slectUserBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if ("".equals(userName.getText()) || "".equals(password.getText())) {
                    ToolUtil.remindMsg("请输入账号和密码");
                    return;
                }

                JSONObject obj = ApiService.getUser(userName.getText(), password.getText());
                account.setText(obj.getString("account"));
                userId.setText(obj.getString("userId"));
            }
        });

        resetPasswordBtn = new MyButton("修改密码");
        resetPasswordBtn.setPreferredSize(new Dimension(100, 25));
        resetPasswordBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ResetPasswordDialog.showDialog(WindowMain.this, userName.getText());
            }
        });

        bt7 = new MyButton("陈欠数据");

        JPanel userPanel = new JPanel();
        userPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        userPanel.add(new JLabel("账号 "));
        userPanel.add(userName);
        userPanel.add(new JLabel("密码"));
        userPanel.add(password);
        userPanel.add(slectUserBtn);
        userPanel.add(resetPasswordBtn);

        userPanel.add(bt7);

        userPanel.add(account);
        userPanel.add(userId);

        JPanel conditionPanel = new JPanel();
        conditionPanel.setPreferredSize(new Dimension(210, 100));
        conditionPanel.setMaximumSize(new Dimension(210, 100));
        conditionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        conditionPanel.add(new JLabel("户号/名称"));
        keyWord = new MJTextField();
        keyWord.setFocusable(true);
        keyWord.setBorder(myLineBorder);
        keyWord.setPreferredSize(new Dimension(110, 25));
        conditionPanel.add(keyWord);

        startMonth = new MonthChooser();
        /*conditionPanel.add(new JLabel("电费开始年月"));
        conditionPanel.add(startMonth);*/

        endMonth = new MonthChooser();
        /*conditionPanel.add(new JLabel("电费结束年月"));
        conditionPanel.add(endMonth);*/

        excelStartDay = new DateChooser();
        conditionPanel.add(new JLabel("导出开始日期"));
        conditionPanel.add(excelStartDay);

        excelEndDay = new DateChooser();
        conditionPanel.add(new JLabel("导出结束日期"));
        conditionPanel.add(excelEndDay);

        JPanel btnPanel = new JPanel();
        btnPanel.setPreferredSize(new Dimension(300, 100));
        btnPanel.setMaximumSize(new Dimension(300, 100));
        btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        btnPanel.setName("btnPanel");
        bt1 = new MyButton("陈欠查询");
        bt2 = new MyButton("陈欠销账");
        bt3 = new MyButton("悔局查询");
        bt4 = new MyButton("悔局销账");
        bt5 = new MyButton("销账导出(个)");
        bt6 = new MyButton("销账导出(全)");


        // 加入到容器即可，无需单独指定大小和位置
        btnPanel.add(bt1);
        btnPanel.add(bt2);
        btnPanel.add(bt3);
        btnPanel.add(bt4);
        btnPanel.add(bt5);
        btnPanel.add(bt6);

        Box textAreaBox = Box.createHorizontalBox();
        textAreaBox.setPreferredSize(new Dimension(400, 100));
        textAreaBox.setMaximumSize(new Dimension(400, 100));
        jTextArea = new JTextArea();
        jTextArea.setEditable(false);
        jTextArea.setRows(2);
        jTextArea.setLineWrap(true);
        jTextArea.setWrapStyleWord(true);
        jTextArea.setFont(new Font("system", Font.PLAIN, 15));

        //设置自动换行
        jTextArea.setLineWrap(true);
        //定义带滚动条的panel，并将JTextArea存入到panel中，使textarea具有滚动条显示功能。
        JScrollPane scrollPane = new JScrollPane(jTextArea);
        //取消显示水平滚动条
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        //显示垂直滚动条
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        textAreaBox.add(scrollPane);

        Box topBox = Box.createVerticalBox();
        topBox.add(userPanel);

        JPanel mainBox = new JPanel();
        mainBox.setLayout(new FlowLayout(FlowLayout.LEFT));
        mainBox.add(textAreaBox);
        mainBox.add(Box.createVerticalBox().add(conditionPanel));
        mainBox.add(Box.createVerticalBox().add(btnPanel));

        Box box = Box.createVerticalBox();
        box.setBorder(new EmptyBorder(10, 10, 10, 10));
        box.add(topBox);
        box.add(mainBox);
        frame.add(box, BorderLayout.NORTH);

        Box webBrowseraBox = Box.createHorizontalBox();
        // 浏览器
        JPanel webBrowserPanel = new JPanel(new GridLayout(0, 1, 0, 0));
        // webBrowserPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        createWebBrowser();

        webBrowserPanel.add(webBrowser);

        webBrowseraBox.add(webBrowserPanel);
        frame.add(webBrowseraBox, BorderLayout.CENTER);

        // 点击事件绑定
        bindClick();

        bindListener();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    /**
     * 浏览器组件初始化
     */
    private static void createWebBrowser() {
        webBrowser = new JWebBrowser();
        webBrowser.navigate(AppConfig.WEB_URL);
        webBrowser.setButtonBarVisible(false);
        webBrowser.setMenuBarVisible(false);
        webBrowser.setBarsVisible(false);
        webBrowser.setStatusBarVisible(false);
    }

    /**
     * 输入框绑定事件
     */
    private static void bindListener() {
        userName.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("userName获取焦点");

                if (webBrowser.getNativeComponent().hasFocus()) {
                    webBrowser.getNativeComponent().requestFocus();
                }

                if (keyWord.hasFocus()) {
                    keyWord.requestFocus(false);
                }

                if (!userName.hasFocus()) {
                    userName.requestFocus(true);
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });

        keyWord.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("keyWord获取焦点");
                if (webBrowser.getNativeComponent().hasFocus()) {
                    webBrowser.getNativeComponent().requestFocus();
                }

                if (userName.hasFocus()) {
                    userName.requestFocus(false);
                }

                if (!keyWord.hasFocus()) {
                    keyWord.requestFocus(true);
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
    }

    /**
     * 按钮点击事件
     */
    private static void bindClick() {

        // 陈欠查询
        bt1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                Toolkit.getDefaultToolkit().getSystemClipboard()
                        .setContents(new StringSelection(keyWord.getText()), null);

                if (StringUtils.isBlank(userId.getText())) {
                    ToolUtil.remindMsg("账号信息为空");
                    return;
                }

                QueryModel queryModel = getQueryModel();
                String info = ApiService.arrearsList(queryModel);
                jTextArea.setText(info);
            }
        });

        // 陈欠销账
        bt2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (StringUtils.isBlank(userId.getText())) {
                    ToolUtil.remindMsg("账号信息为空");
                    return;
                }

                QueryModel queryModel = getQueryModel();
                String info = ApiService.payRecord(queryModel);
                jTextArea.setText(info);
            }
        });

        // 悔局查询
        bt3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (StringUtils.isBlank(userId.getText())) {
                    ToolUtil.remindMsg("账号信息为空");
                    return;
                }

                QueryModel queryModel = getQueryModel();
                String info = ApiService.regretList(queryModel);
                jTextArea.setText(info);
            }
        });

        // 悔局
        bt4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (StringUtils.isBlank(userId.getText())) {
                    ToolUtil.remindMsg("账号信息为空");
                    return;
                }

                QueryModel queryModel = getQueryModel();
                String info = ApiService.regretDel(queryModel);
                jTextArea.setText(info);
            }
        });

        // 导出
        bt5.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (StringUtils.isBlank(userId.getText())) {
                    ToolUtil.remindMsg("账号信息为空");
                    return;
                }

                ExcelModel excelModel = getExcelModel("0");
                File info = ApiService.excelResult(excelModel);
                jTextArea.setText("文件路径: " + info.getAbsolutePath());
            }
        });

        // 导出全部
        bt6.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (StringUtils.isBlank(userId.getText())) {
                    ToolUtil.remindMsg("账号信息为空");
                    return;
                }

                ExcelModel excelModel = getExcelModel("1");
                File info = ApiService.excelResult(excelModel);
                jTextArea.setText("文件路径: " + info.getAbsolutePath());
            }
        });

        bt7.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (StringUtils.isBlank(userId.getText())) {
                    ToolUtil.remindMsg("账号信息为空");
                    return;
                }
                if (!userId.getText().equals("1402877574933127169")) {
                    ToolUtil.remindMsg("暂无权限");
                    return;
                }
                ExcelModel excelModel = getExcelModel("1");
                File info = ApiService.downExcelRecord(excelModel);
                jTextArea.setText("文件路径: " + info.getAbsolutePath());
            }
        });

    }

    /**
     * 导出参数构建
     *
     * @param s
     * @return
     */
    private static ExcelModel getExcelModel(String s) {
        ExcelModel excelModel = new ExcelModel();
        excelModel.setAccount(userId.getText());
        excelModel.setIsMyself(s);
        excelModel.setExcelStartDay((StringUtils.isBlank(excelStartDay.getShowDate().getText()) || "选择".equals(excelStartDay.getShowDate().getText()))
                ? null : excelStartDay.getShowDate().getText());
        excelModel.setExcelEndDay((StringUtils.isBlank(excelEndDay.getShowDate().getText()) || "选择".equals(excelEndDay.getShowDate().getText()))
                ? null : excelEndDay.getShowDate().getText());

        System.out.println("excelModel = " + excelModel.toString());
        return excelModel;
    }

    /**
     * 查询参数构建
     *
     * @return
     */
    private static QueryModel getQueryModel() {
        QueryModel queryModel = new QueryModel();
        queryModel.setAccount(userId.getText());
        queryModel.setKeyWord(StringUtils.isBlank(keyWord.getText()) ? null : keyWord.getText());
        queryModel.setStartMonth((StringUtils.isBlank(startMonth.getShowDate().getText()) || "选择".equals(startMonth.getShowDate().getText()))
                ? null : startMonth.getShowDate().getText().replaceAll("-", ""));
        queryModel.setEndMonth((StringUtils.isBlank(endMonth.getShowDate().getText()) || "选择".equals(endMonth.getShowDate().getText()))
                ? null : endMonth.getShowDate().getText().replaceAll("-", ""));

        System.out.println("queryModel = " + queryModel.toString());
        return queryModel;
    }

}
